from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from jwt import ExpiredSignatureError, InvalidTokenError, PyJWTError
from rest_framework_jwt.settings import api_settings


# 鉴权中间件
class JwtAuthenticationMiddleware(MiddlewareMixin):

    def process_request(self, request):
        return None  # 测试环境
        white_list = ['/login', '/article/selectAll', '/articleType/select']  # 白名单
        if request.path not in white_list and not request.path.startswith('/media'):  # 不在白名单和媒体文件需要进行校验
            token = request.META.get('HTTP_AUTHORIZATION')
            try:
                jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
                jwt_decode_handler(token)  # 解析token
            except ExpiredSignatureError:
                return HttpResponse("Token过期,重新登录！")
            except InvalidTokenError:
                return HttpResponse("Token验证失败！")
            except PyJWTError:
                return HttpResponse("Token验证异常！")
            print(token)
        else:
            print("鉴权中间件:不验证")
            return None
